<?php
namespace Wx\Controller;
use Think\Controller;
class GoodsController extends Controller {
    //订单详情
    public  function index(){
        $id=I('get.goodsId');
        $isgroup=I('get.group');
        $isSecKill=I('get.secKill');
        //session('oto_userId',257);
        if(session('oto_userId')){
            $this->isLogin = 1;
        }
        //判断此团购是否有效
        if($isgroup){
            $sql="select id,groupPrice,groupMaxCount from oto_goods_group WHERE unix_timestamp(now()) BETWEEN startTime AND endTime and goodsGroupStatus=1 and groupStatus=1 and goodsId=".$id;
            $group=M()->query($sql);
            if($group){
                $this->isgroup=1;
            }else{
                $this->isgroup=0;
            }
        }else{
            $this->isgroup=0;
        }
        //判断此秒杀是否有效
        if($isSecKill){
            $sql="select id,seckillPrice,seckillMaxCount from oto_goods_seckill WHERE unix_timestamp(now()) BETWEEN  seckillStartTime AND seckillEndTime and goodsSeckillStatus=1 and seckillStatus=1 and goodsId= ".$id;
            $seckill=M()->query($sql);
            if($seckill){
                $this->isSeckill=1;
            }else{
                $this->isSeckill=0;
            }
        }else{
            $this->isSeckill=0;
        }
        $filed="g.goodsSn,g.shopId,g.goodsName,g.marketPrice,g.shopPrice,g.goodsStock,g.goodsUnit,g.goodsDesc,g.goodsId,g.goodsThums,g.goodsImg";
        $map['g.goodsFlag']=1;
        $map['g.goodsId']=$id;
        $map['g.goodsStatus']=1;
        $goodsInfo=M('goods as g')->field($filed)->where($map)->find();
        $goodsInfo['goodsDesc']=html_entity_decode($goodsInfo['goodsDesc']);

        $temp = [
            'goodsPri'=> $goodsInfo['shopPrice'],
            'goodsId' => $goodsInfo['goodsId'],
            'goodsPic'=> $goodsInfo['goodsThums'],
        ];
        $this->info = json_encode($temp);


        //如果是团购，则使用团购价
        if($isgroup&&$group[0]['groupPrice']){
            $goodsInfo['shopPrice']=$group[0]['groupPrice'];
            $goodsInfo['maxNum']=$group[0]['groupMaxCount'];
            $goodsInfo['goodsType']= 'isGroup';
            $goodsInfo['groupId']= $group[0]['id'];

        }
        if($goodsInfo){
            $goodsInfo['groupId']=$goodsInfo['groupId']?$goodsInfo['groupId']:0;
        }
        //如果是秒杀，则使用秒杀价
        if($isSecKill&&$seckill[0]['seckillPrice']){
            $goodsInfo['shopPrice']=$seckill[0]['seckillPrice'];
            $goodsInfo['maxNum']=$seckill[0]['seckillMaxCount'];
            $goodsInfo['goodsType']= 'isSecKill';
            $goodsInfo['seckillId']= $seckill[0]['id'];
        }
        //图片轮播
        $scrollImg=M('goods_gallerys')->where(array('goodsId'=>$id))->field('goodsImg')->select();
        //是否关注
        // $isAttentition=M('favorites')->where(array('targetId'=>$id,'favoriteType'=>0))->find();
        // if($isAttentition){
        //     $goodsInfo['attentition']=1;
        // }else{
        //     $goodsInfo['attentition']=0;
        // }
        //商品属性
        // $attrMap['g.goodsId']=$id;
        // $attrMap['a.isPriceAttr']=1;
        // $attrMap['a.attrFlag']=1;
        // $attrField="g.goodsId,g.attrVal,a.attrName";
        // $attr=M('goods_attributes')->where($attrMap)->field($attrField)->join('as g left join oto_attributes as a on a.attrId=g.attrId')->select();
        // $this->assign('attr',$attr);
        //dump($attr);die;
        //用户默认地址
        // $userAddr=M('user_address')->where(array('userId'=>session('oto_userId'),'isDefault'=>1,'addressFlag'=>1))->find();
        // $areaDb=M('areas');
        // $userAddr['province']=$areaDb->where(array('areaId'=>$userAddr['areaId1']))->getField('areaName');
        // $userAddr['city']=$areaDb->where(array('areaId'=>$userAddr['areaId2']))->getField('areaName');
        // $userAddr['area']=$areaDb->where(array('areaId'=>$userAddr['areaId3']))->getField('areaName');
        // $userAddr['communitys']=M('communitys')->where(array('communityId'=>$userAddr['communityId']))->getField('communityName');
        // $this->userAddr=$userAddr;
        $goodsImgs = M('goods_gallerys')->field('goodsImg')->where(array('goodsId'=>$id))->select();
        $this->goodsImgs = $goodsImgs;

        //月销量
        $m_map['g.goodsId']=$id;
        $m_map['o.orderStatus']=array('egt',0);
        $m_time=time();
        $m_map['_string']="(paytime-$m_time)<2592000";
        $monthCount=M('order_goods')->where($m_map)->join('as g left join oto_orders as o on g.orderId=o.orderId')->sum('g.goodsNums');
        if(empty($monthCount)){
            $monthCount=0;
        }

        $goodsInfo['monthCount']=$monthCount;

        //销售属性 如：颜色尺码 ，不同价格
        $saleAttr['g.goodsId']=$id;
        $saleAttr['a.isPriceAttr']=1;//价格属性
        $saleAttr['a.attrFlag']=1;
        $saleAttrField="g.goodsId,g.attrId,g.attrPrice,g.attrStock,g.attrVal,g.id";
        $saleAttrInfo=M('goods_attributes')->where($saleAttr)->field($saleAttrField)->join('as g left join oto_attributes as a on a.attrId=g.attrId')->select();

        if($saleAttrInfo){
            $goodsTotal=0;
            foreach ($saleAttrInfo as $k=>$v){
                $goodsTotal+=$v['attrStock'];
            }
            //库存为所有属性总和
            $goodsInfo['goodsStock']=$goodsTotal;
        }
        $parentAttrField="a.shopId,a.catId,a.attrName,a.attrId";
        $parentAttrInfo=M('goods_attributes')->where($saleAttr)->field($parentAttrField)->join('as g left join oto_attributes as a on a.attrId=g.attrId')->group('attrId')->select();
        //echo M()->getLastSql();die;
        //dump($parentAttrInfo);die;
        foreach ($parentAttrInfo as $k=>$v){
           foreach ($saleAttrInfo as $kk=>$vv){
               if($v['attrId']==$vv['attrId']){
                    $parentAttrInfo[$k]['child'][$kk]=$vv;
                    $parentAttrInfo[$k]['child'][$kk]['json']=json_encode($vv);

               }
           }
        }

        //header('content-type:text/html; charset=utf8');
        //dump($parentAttrInfo);die;
        //print_r($parentAttrInfo);die;
//      p($parentAttrInfo);return;
        $this->assign('saleAttr',$parentAttrInfo);
        //dump($parentAttrInfo);die;
        //评价晒单
        //$share_db=M('share');
        //$shareMap['goodsId']=$id;
//      $shareField="u.userId,u.userName,s.goodsId,s.shareTitle,s.shareContent,s.shareImg1,s.shareImg2,s.shareImg3,s.shareImg4,s.shareTime,s.star,(4-s.star) as star_";
//      $countShare=$share_db->where($shareMap)->count();
//      $avgShare=$share_db->where($shareMap)->avg('star');
//      $avgShare=($avgShare/5)*100;
//      $shareInfo=$share_db->where($shareMap)->field($shareField)->join('as s left join oto_users as u on u.userId=s.userId')->limit(5)->select();
//
//
        //$shareMap['goodsId']=$id;
//      $shareField="u.userId,u.userName,s.goodsId,s.shareTitle,s.shareContent,s.shareImg1,s.shareImg2,s.shareImg3,s.shareImg4,s.shareTime,s.star,(4-s.star) as star_";
//      $countShare=$share_db->where($shareMap)->count();
        //$avgShare=$share_db->where($shareMap)->avg('star');
//      $avgShare=($avgShare/5)*100;
//      $shareInfo=$share_db->where($shareMap)->field($shareField)->join('as s left join oto_users as u on u.userId=s.userId')->limit(5)->select();


        // $sql ="SELECT ga.goodsScore as star
        //         FROM (__PREFIX__goods_appraises ga , __PREFIX__orders od , __PREFIX__users u) left join __PREFIX__share s on s.orderId = ga.orderId AND s.goodsId = ga.goodsId
        //         WHERE ga.userId = u.userId AND ga.orderId = od.orderId AND ga.goodsId = $id   group by ga.id";

        // $countShare = M()->query($sql);
        // $countShare = count($countShare);


        // $sql = "SELECT AVG (ga.goodsScore) as a
        //         FROM (__PREFIX__goods_appraises ga , __PREFIX__orders od , __PREFIX__users u) left join __PREFIX__share s on s.orderId = ga.orderId AND s.goodsId = ga.goodsId
        //         WHERE ga.userId = u.userId AND ga.orderId = od.orderId AND ga.goodsId = $id   group by ga.id order by ga.id desc";

        // $avgShare = M()->query($sql);
        // $avgShare =$avgShare[0]['a'];


        // $avgShare=(int)(($avgShare/5)*100);




        // $sql ="SELECT ga.goodsScore as star,ga.userId,(5-ga.goodsScore) as star_, u.userName,s.shareImg1,s.shareImg2,s.shareImg3,s.shareImg4,s.isShow,s.anonymity,s.shareTitle,s.goodsId,s.id,ga.createTime as shareTime,ga.content as shareContent
        //         FROM (__PREFIX__goods_appraises ga , __PREFIX__orders od , __PREFIX__users u) left join __PREFIX__share s on s.orderId = ga.orderId AND s.goodsId = ga.goodsId
        //         WHERE ga.userId = u.userId AND ga.orderId = od.orderId AND ga.goodsId = $id   group by ga.id order by ga.id desc  limit 5";

        // $shareInfo = M()->query($sql);
//        $countShare = count($shareInfo);
//            $shareInfo=$share_db->where($shareMap)->field($shareField)->join('as s left join oto_users as u on u.userId=s.userId')->limit(5)->select();

        $this->assign('shareCount',array('total'=>$countShare,'star'=>$avgShare));
        //$this->assign('shareInfo',$shareInfo);
        //$this->assign('cityInfo',$this->cityInfo);
        $this->assign('scrollImg',$scrollImg);
        //print_r($goodsInfo);
        $this->assign('goodsInfo',$goodsInfo);
        $this->assign('goodsCnt',$this->getCartGoodCnt());
        $this->assign('shopComment',D('Shop')->getComment());

        //购物车是否已经有此产品
        $carInfo=M('car_session')->where(array('userId'=>session('oto_userId')))->getField('car_session');
        $carInfo=unserialize($carInfo);
        $select=array();
        foreach ($carInfo as $k=>$v){
            $attr='';
            if($id==$v['goodsId']){
                foreach ($v as $kk=>$vv){
                    if(is_numeric($kk)){
                       $attr.=$vv['attrName'].':'.$vv['attrVal'].' '.',';
                    }
                }
                $attr=trim($attr,',');
                $select[]=array('goodsName'=>$v['goodsName'],'goodsAttr'=>$attr);
            }
        }
        $this->select=$select;


        //购物车金额与数量
        $cartInfo = D('Cart')->getCartInfo();


        $goods_num = 0;
        $goods_list = [];
        $id = $goodsInfo['shopId'];
        $totalMoney = 0;
        if($cartInfo['cartgoods'][$id]['shopgoods']){
            // foreach ($cartInfo['cartgoods'][$id]['shopgoods'] as  $value) {
            //     if($value['isGroup']==0&&$value['isSeckill']==0){//不显示秒杀商品和团购商品

            //         $totalMoney += ($value[0]?$value[0]['shopPrice']:$value['shopPrice'])*$value['cnt'];
            //         $goods_num+=$value['cnt'];
            //         $goods_list[$value['goodsId']] = $value;
            //     }

            // }
            //
            foreach ($cartInfo['cartgoods'][$id]['shopgoods'] as  $value) {

                if($value['isGroup']==0&&$value['isSeckill']==0){//不显示秒杀商品和团购商品
                    $value['attrId'] = '';
                    if($value['goodsAttrId']){//是否属性商品
                        $num = count(explode('_',$value['goodsAttrId']));
                        $tempMoney = 0;
                        $value['attrName']='';
                        //属性商品价格相加
                        for($i=0;$i<$num;$i++){
                            $tempMoney += $value[$i]['shopPrice'];
                            $value['attrName'].= "【{$value[$i]['attrName']}】";
                        }
                        // $totalMoney+=$tempMoney*$value['cnt'];
                        $value['shopPrice'] = $tempMoney;
                        $value['attrId'] = implode(',',explode('_',$value['goodsAttrId']));
                    }

                    $totalMoney += $value['shopPrice']*$value['cnt'];

                    $goods_num += $value['cnt'];
                    //$attrId = $value[0]['goodsAttrId']?$value[0]['goodsAttrId']:0;
                    $goods_list["{$value['goodsId']}_{$goodsAttrId}"] = $value;
                }

            }
        }
       // $this->totalMoney = $cartInfo['totalMoney'];
        $this->totalMoney = $totalMoney;
        $this->number = $goods_num;
        //dump(I('ref'));die;
        //上一页url
        if(I('ref')){
            $this->ref = I('ref').'/goodsDetail/1';
        }else{
            $this->ref = 'javascript:history.back(-1);';
        }

        $this->display();
    }

    /**
     * 获取购物车商品数量
     */
    public function getCartGoodCnt(){
        $map['userId']= session('oto_userId');
        $isCarExists=M('car_session')->where($map)->field('car_session,userId')->find();
        if($isCarExists){
            $shopcart=unserialize($isCarExists['car_session']);
            $goodsCut=count($shopcart);
            if(IS_AJAX){
                if($goodsCut){
                    $this->ajaxReturn(array('goodscnt'=>$goodsCut));
                }else {
                    $this->ajaxReturn(array('goodscnt'=>0));
                }
            }else{
                return $goodsCut;
            }
        }else{
            if(IS_AJAX){
                  $this->ajaxReturn(array('goodscnt'=>0));
            }else{
                return 0;
            }
        }
    }

    /**
     * 获取商品库存
     *
     */
    public function getGoodsStock(){
        $data = array();
        $data['goodsId'] = (int)I('goodsId');
        $data['isBook'] = (int)I('isBook');
        $data['goodsAttrId'] = (int)I('goodsAttrId');
        $data['isGroup']=I('isGround',0,intval);
        $data['isSeckill']=I('isSeckill',0,intval);
        $goods = D('Wx/Cart');
        $goodsStock = $goods->getGoodsStock($data);
        echo json_encode($goodsStock);

    }

}

